'use client'

import { lazy, Suspense, ComponentType } from 'react'
import { LoadingSpinner } from './LoadingSpinner'

// 懒加载主要组件 - 使用动态导入和 webpackChunkName
export const LazyViewer3D = lazy(() =>
    import(/* webpackChunkName: "viewer-3d" */ './Viewer3D').then(module => ({ default: module.Viewer3D }))
)

export const LazyViewer2D = lazy(() =>
    import(/* webpackChunkName: "viewer-2d" */ './Viewer2D').then(module => ({ default: module.Viewer2D }))
)

export const LazyTaskSelector = lazy(() =>
    import(/* webpackChunkName: "task-selector" */ './TaskSelector').then(module => ({ default: module.TaskSelector }))
)

export const LazyTaskExecution = lazy(() =>
    import(/* webpackChunkName: "task-execution" */ './TaskExecution').then(module => ({ default: module.TaskExecution }))
)

export const LazyTaskResultDisplay = lazy(() =>
    import(/* webpackChunkName: "task-result" */ './TaskResultDisplay').then(module => ({ default: module.TaskResultDisplay }))
)

// 懒加载面板组件
export const LazyAxialPanel = lazy(() =>
    import(/* webpackChunkName: "panels" */ './panels/AxialPanel').then(module => ({ default: module.AxialPanel }))
)

export const LazySagittalPanel = lazy(() =>
    import(/* webpackChunkName: "panels" */ './panels/SagittalPanel').then(module => ({ default: module.SagittalPanel }))
)

export const LazyCoronalPanel = lazy(() =>
    import(/* webpackChunkName: "panels" */ './panels/CoronalPanel').then(module => ({ default: module.CoronalPanel }))
)

export const LazyMainPanel = lazy(() =>
    import(/* webpackChunkName: "panels" */ './panels/MainPanel').then(module => ({ default: module.MainPanel }))
)

export const LazyAuxPanel = lazy(() =>
    import(/* webpackChunkName: "panels" */ './panels/AuxPanel').then(module => ({ default: module.AuxPanel }))
)

// 懒加载开发工具
export const LazyDevTools = lazy(() =>
    import(/* webpackChunkName: "dev-tools" */ './DevTools/DevToolsPanel').then(module => ({ default: module.DevToolsPanel }))
)

// 懒加载图像查看器组件
export const LazyImageViewer = lazy(() =>
    import(/* webpackChunkName: "image-viewer" */ './ImageViewer/ImageControls')
)

// 懒加载反馈系统 - 通知容器
export const LazyNotificationContainer = lazy(() =>
    import(/* webpackChunkName: "feedback" */ './Feedback/NotificationSystem').then(module => ({ default: module.NotificationContainer }))
)

// 高阶组件：为懒加载组件添加 Suspense 包装和错误边界
export function withLazyLoading<T extends object>(
    LazyComponent: React.LazyExoticComponent<ComponentType<T>>,
    options?: {
        fallback?: React.ReactNode
        chunkName?: string
        preload?: boolean
    }
) {
    const WrappedComponent = function LazyWrapper(props: T) {
        return (
            <Suspense fallback={options?.fallback || <LoadingSpinner />}>
                <LazyComponent {...props} />
            </Suspense>
        )
    }

    // 添加预加载功能
    if (options?.preload) {
        WrappedComponent.preload = () => LazyComponent
    }

    return WrappedComponent
}

// 预制的包装组件
export const Viewer3DLazy = withLazyLoading(LazyViewer3D, {
    fallback: <LoadingSpinner tip="加载3D查看器..." />,
    preload: true
})

export const Viewer2DLazy = withLazyLoading(LazyViewer2D, {
    fallback: <LoadingSpinner tip="加载2D查看器..." />,
    preload: true
})

export const TaskSelectorLazy = withLazyLoading(LazyTaskSelector, {
    fallback: <LoadingSpinner tip="加载任务选择器..." />
})

export const TaskExecutionLazy = withLazyLoading(LazyTaskExecution, {
    fallback: <LoadingSpinner tip="加载任务执行器..." />
})

export const TaskResultDisplayLazy = withLazyLoading(LazyTaskResultDisplay, {
    fallback: <LoadingSpinner tip="加载结果显示..." />
})

export const DevToolsLazy = withLazyLoading(LazyDevTools, {
    fallback: <LoadingSpinner tip="加载开发工具..." />
})

// 组件预加载管理器
export class ComponentPreloader {
    private static preloadedComponents = new Set<string>()

    static async preloadComponent(componentName: keyof typeof preloadMap) {
        if (this.preloadedComponents.has(componentName)) {
            return
        }

        try {
            await preloadMap[componentName]()
            this.preloadedComponents.add(componentName)
        } catch (error) {
            console.warn(`Failed to preload component ${componentName}:`, error)
        }
    }

    static async preloadCriticalComponents() {
        const criticalComponents: (keyof typeof preloadMap)[] = ['viewer3d', 'viewer2d', 'toolbox']
        await Promise.allSettled(
            criticalComponents.map(component => this.preloadComponent(component))
        )
    }

    static isPreloaded(componentName: string): boolean {
        return this.preloadedComponents.has(componentName)
    }
}

// 预加载映射
const preloadMap = {
    viewer3d: () => import('./Viewer3D'),
    viewer2d: () => import('./Viewer2D'),
    taskSelector: () => import('./TaskSelector'),
    taskExecution: () => import('./TaskExecution'),
    taskResult: () => import('./TaskResultDisplay'),
    devTools: () => import('./DevTools/DevToolsPanel'),
    toolbox: () => import('./Toolbox'),
    imageViewer: () => import('./ImageViewer'),
    feedback: () => import('./Feedback/FeedbackSystem')
}

// React Hook for component preloading
export function useComponentPreloader() {
    const preloadComponent = (componentName: keyof typeof preloadMap) => {
        return ComponentPreloader.preloadComponent(componentName)
    }

    const preloadCritical = () => {
        return ComponentPreloader.preloadCriticalComponents()
    }

    const isPreloaded = (componentName: string) => {
        return ComponentPreloader.isPreloaded(componentName)
    }

    return {
        preloadComponent,
        preloadCritical,
        isPreloaded
    }
}